package com.demo.dao.impl;

import com.demo.dao.CustomerDao;
import com.demo.domain.Customer;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {
    @Override
    public void save(Customer customer) {

        getHibernateTemplate().save(customer);
    }

    @Override
    public List<Customer> find() {
        List<Customer> list = (List<Customer>) getHibernateTemplate().find(
                "from Customer ");
        return list;
    }

    @Override
    public Customer findOne(int cust_id) {
        return getHibernateTemplate().get(Customer.class, cust_id);
    }

    @Override
    public void delete(Customer c) {
        getHibernateTemplate().delete(c);
    }

    @Override
    public void update(Customer customer) {
        getHibernateTemplate().update(customer);
    }

    @Override
    public List<Customer> findCondition(Customer customer) {
        List<Customer> list = (List<Customer>) getHibernateTemplate().find(
                "from Customer where cust_name like ?",
                "%" + customer.getCust_name() + "%");
        return list;
    }

    public List<Customer> findMoreCondition(Customer customer) {
        // TODO Auto-generated method stub
        // 创建离线对象，指定对哪个实体类进行操作
        DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
        // 判断条件值是否为空
        if (customer.getCust_name() != null
                && !"".equals(customer.getCust_name())) {
            // 设置对属性，设置值
            criteria.add(Restrictions.eq("cust_name", customer.getCust_name()));
        }
        // if (customer.getCustLevel() != null
        // && !"".equals(customer.getCustLevel())) {
        // criteria.add(Restrictions.eq("custLevel", customer.getCustLevel()));
        // }
        if (customer.getCust_source() != null
                && !"".equals(customer.getCust_source())) {
            criteria.add(Restrictions.eq("cust_source",
                    customer.getCust_source()));
        }

        return (List<Customer>) this.getHibernateTemplate().findByCriteria(
                criteria);

    }
}
